package com.csmk.springboot_simple.base;

import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.service.IService;


import com.csmk.springboot_simple.exception.ServiceException;
import com.csmk.springboot_simple.util.IDGenerator;
import com.csmk.springboot_simple.util.Null;
import com.csmk.springboot_simple.util.SpringUtils;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 基础服务类 mybatis-plus加强
 * 封装service通用代码
 *
 * @param <T>
 */
public interface BaseService<T> extends IService<T> {

    /**
     * 获取String参数
     */
    default String getParameter(String name) {
        return getRequest().getParameter(name);
    }


    default <T> T getParameter(String name, Class<T> type) {
        return Convert.convert(type, getRequest().getParameter(name));
    }


    /**
     * 获取request
     */
    default HttpServletRequest getRequest() {
        return getRequestAttributes().getRequest();
    }

    /**
     * 获取response
     */
    default HttpServletResponse getResponse() {
        return getRequestAttributes().getResponse();
    }

    /**
     * 获取session
     */
    default HttpSession getSession() {
        return getRequest().getSession();
    }

    default ServletRequestAttributes getRequestAttributes() {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        return (ServletRequestAttributes) attributes;
    }

    /**
     * 将字符串渲染到客户端
     *
     * @param response 渲染对象
     * @param string   待渲染的字符串
     */
    default void renderString(HttpServletResponse response, String string) {
        try {
            response.setStatus(200);
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(string);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    default void error() {
        error("操作失败");
    }

    default void error(String msg) {
        throw new ServiceException(msg);
    }

    /**
     * 获取请求体中的字符串
     *
     * @return 请求体
     * @throws IOException
     */
    default String getRequestBodyJson() throws IOException {
        HttpServletRequest request = getRequest();
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = null;
        try {
            bufferedReader = request.getReader();
            char[] charBuffer = new char[128];
            int bytesRead;
            while ((bytesRead = bufferedReader.read(charBuffer)) != -1) {
                stringBuilder.append(charBuffer, 0, bytesRead);
            }
        } finally {
            if (bufferedReader != null) {
                bufferedReader.close();
            }
        }

        return stringBuilder.toString();

    }

    default <V> V getRequestBody(Class<V> clz) {
        try {
            return JSON.parseObject(getRequestBodyJson(), clz);
        } catch (IOException e) {
            throw new ServiceException("请求体解析异常");
        }
    }

    default boolean isEmpty(Object... objs) {
        return Null.isEmpty(objs);
    }

    default boolean isEmpty(Object obj) {
        return Null.isEmpty(obj);
    }

    default boolean isNotEmpty(Object obj) {
        return !isEmpty(obj);
    }

    default boolean isBlank(CharSequence cs) {
        return Null.isBlank(cs);
    }

    // 向前端写出文件
    default void writeFile(File file) throws IOException {
        if (!file.exists()) {
            IOUtils.copy(FileUtils.openInputStream(file), getResponse().getOutputStream());
        }
    }

    // 保存文件到本地
    default String saveFile(MultipartFile webFile){
        if (webFile == null || webFile.isEmpty()) {
            throw new ServiceException("文件为空");
        }
        String uploadDir = SpringUtils.getRequiredProperty("resource.base-dir");

        // 定义文件保存路径，可以根据实际情况修改
        File uploadPath = new File(uploadDir);
        // 如果目录不存在，则创建目录
        if (!uploadPath.exists()) {
            uploadPath.mkdirs();
        }

        // 构建文件保存路径
        String originalFileName = webFile.getOriginalFilename();
        String fileNameWithoutExtension = originalFileName.substring(0, originalFileName.lastIndexOf('.'));
        String fileExtension = originalFileName.substring(originalFileName.lastIndexOf('.'));
        String timestamp = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        String newFileName = fileNameWithoutExtension + "_" + timestamp + fileExtension;
        File destFile = new File(uploadPath, newFileName);

        try {
            // 将文件保存到本地
            webFile.transferTo(destFile);
            return newFileName;
        } catch (IOException e) {
            e.printStackTrace();
            throw new ServiceException("上传失败，未知异常");
        }
    }

    default Long genId() {
        return IDGenerator.get();
    }

    default <T> T getBean(Class<T> clz) {
        return SpringUtils.getBean(clz);
    }
    int saveOrUpdateAll(List<T> list);
}
